#include <stdio.h>
#include <stdlib.h>
#include "h/list.h"

static void CopyToNode(Item, Node *);

void InitializeList(List * plist)
{
    *plist = NULL;
}

bool ListIsEmpty(const List * plist)
{
    return *plist == NULL;
}

bool ListIsFull()
{
    bool is_full = false;
    Node * pt = malloc(sizeof(Node));

    if (NULL == pt)
        is_full = true;
    else
        free(pt);

    return is_full;
}

unsigned ListItemCount(const List * plist)
{
    Node * node = *plist;
    unsigned i = 0;

    while (node) {
        ++i;
        node = node->next;
    }

    return i;
}

bool AddItem(Item item, List * plist)
{
    Node * tail = *plist;
    Node * new = malloc(sizeof(Node));

    if (NULL == new)
        return false;

    CopyToNode(item, new);
    new->next = NULL;

    while (tail && tail->next != NULL)
        tail = tail->next;

    if (NULL == tail)
        *plist = new;
    else
        tail->next = new;

    return true;
}

void Traverse(const List * plist, void (* call)(const Item *))
{
    Node * curr = * plist;
    while (curr != NULL) {
        call(&curr->item);
        curr = curr->next;
    }
}

void EmptyTheList(List * plist)
{
    Node * curr = * plist;

    while (curr != NULL) {
       * plist = (*plist)->next;

       free(curr);
       curr = *plist;
    }

}

static void CopyToNode(Item item, Node * node)
{
    node->item = item;
}

